'''
Script to update package on a running node.
Created on 08/12/2009

@author: eh01
'''
from datastore.resource import Resource
from optparse import OptionParser
import os
import sys
import urllib2

if __name__ == '__main__':
    
    parser = OptionParser(usage=u"%s options." % sys.argv[0])

    parser.add_option("-t", "--test",
    dest=u"test", action="store_true", default=True,
    help=u"Test retrieves the packages from your local distribution directory.")
    
    parser.add_option("-d", "--distributiondirectory",
    dest=u"distribution_directory",
    help=u"Absolute Path to the directory where the package is located.")    

    parser.add_option("-v", "--version",
    dest=u"version", 
    help=u"Version of the package to install. e.g. X.X.X")
    
    parser.add_option("-p", "--package_name",
    dest=u"package_name",
    help=u"Name of the package to install.")
    
    (options, args) = parser.parse_args()
    options.script = os.path.split(sys.argv[0])[1]
    
    path_to_package_file = os.path.join(options.distribution_directory, options.package_name + '_v' + options.version + '.yarra')

    res = Resource()
    
    if options.test:
        package_url = 'http://localhost:8000/terms/base/package/' + options.package_name
        res.url = 'file:///' + path_to_package_file
    else:
        # this is when we are going to update for a production node. In this case the url will be pointing to a 
        # package built for production.
        pass
    
    serialised_resource = res.serialise()
    
    opener = urllib2.build_opener()
    request = urllib2.Request(package_url, data=serialised_resource)
    request.get_method = lambda: 'PUT'
    handle = opener.open(request)
    response_content = handle.read()    
